﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;

namespace EasyDDD.Host.WebAPI
{
    /// <summary>
    /// 根据HttpContext.Request.Path判断权限
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class AuthorizeUrlAttribute : Attribute, IAuthorizationFilter
    {
        string Path { get; set; } = string.Empty;

        public AuthorizeUrlAttribute()
        {
        }

        public AuthorizeUrlAttribute(string path)
        {
            this.Path = path;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if (context.HttpContext.User.Identity?.Name == "superadmin")
            {
                return;
            }
            if (context.HttpContext.User.IsInRole("superadmin"))
            {
                return;
            }
            if (context.HttpContext.User.HasClaim(ClaimTypes.Role, "superadmin"))
            {
                return;
            }

            if (!string.IsNullOrEmpty(this.Path))
            {
                Path = context.HttpContext.Request.Path;
            }
            if (!context.HttpContext.User.HasClaim(ClaimTypes.Role, Path))
            {
                throw new Exception("您没有该权限！");
            }
        }
    }
}